<?php

namespace App\Http\Controllers;

use App\Exports\FangOwnerExport;
use App\Models\Detailed;
use App\Models\GoodsModel;
use App\Models\Records;
use App\Models\Rule;
use Elastic\Elasticsearch\ClientBuilder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class GoodsController extends Controller
{
    public function GoodsList(Request $request)
    {
        $data = GoodsModel::paginate(1);
        return $data;
    }

    /**
     * Name: ES添加
     * User: Zhao
     * Date: 2023/6/19
     * Time:10:04
     * @param Request $request
     * @return mixed
     */
    public function orderCreate(Request $request)
        {
        $para = $request->post();
        unset($para['_token']);
        $data = GoodsModel::create($para);
        if ($data) {
            $client = ClientBuilder::create()
                ->setHosts(['127.0.0.1:9200'])
                ->build();
            $params = [
                'index' => 'index',
                'id' => $data->id,
                'body' => $data->toArray()
            ];
            $results = $client->search($params);
        }
        return $data;
    }

    /**
     * Name: es搜索
     * User: Zhao
     * Date: 2023/6/19
     * Time:10:04
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\View\View|\think\response\View
     */
    public function listd(Request $request){
        $id = $request->get('id');
        $para = $request->get('search');
        $obj = new GoodsModel();
        if ($para){
            $host=['127.0.0.1'];
            $client = ClientBuilder::create()
                ->setHosts($host)
                ->build();
            $params = [
                'index' => 'jk',
                'body'  => [
                    'query' => [
                        'match' => [
                            'goods_name' => $para
                        ]
                    ]
                ]
            ];
            $results = $client->search($params);
//                dd($results);
        }
        $data = $obj->paginate(4);
        return view('list',['data'=>$data]);
    }

    /**
     * Name: 导出数据表的数据
     * User: Zhao
     * Date: 2023/6/18
     * Time:16:26
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function exports(){
        return Excel::download(new FangOwnerExport(),'导出的数据.xlsx');
    }

    /**
     * Name: 签到功能
     * User: Zhao
     * Date: 2023/6/19
     * Time:14:48
     * @return array
     * @throws \Throwable
     */
    public function signin(){
        $userId =1;
        $user = \App\Models\Login::where('id',$userId)->first();
        $day = $user->days;
        //获取当前的时间
        $yearMonthDay = date('Y-m-d',time());
        $has =  Records::where('userid',$userId)->where('ymd',$yearMonthDay)->first();
        if($has)
        {
            return ['code'=>200,'msg'=>'已签到','data'=>[]];
        }

        //开启事务
        DB::beginTransaction();
        try {
//            echo 1;die;
            //将用户id 和 当前签到天数添加到表里面
            $sign = Records::insert(['userid'=>$userId,'ymd'=>$yearMonthDay]);
            $signId = $sign->id;
            //获取用户上次签到时间
            $lastSignDayObj = Records::select('ymd')->where('userid',$userId)->where('id','<',$signId)->orderBy('id','desc')->limit(1)->first();
            //根据上次的签到时间来判断是 断签 ，还是连续签到 ，还是第一次签到
            if (empty($lastSignDayObj)){
                //不存在 表示第一次签到
                $days = 1;
                $number = Rule::select('number')->where('day',$days)->first();
                if ($number){
                    $score = $number->number;
                    //存在
                }else{
                    //不存在
                    $score = 7;
                }
                $status = '第一次签到,获得积分'.$score;
            }else{
                $lastSignDay = $lastSignDayObj->ymd;
                //存在  将当前天数的时间戳 和 上次签到的时间戳作比较
                $time = strtotime($yearMonthDay) - strtotime($lastSignDay);
                if ($time >= 24*3600 && $time < 48*3600){
                    //表示连续签到 签到天数加一
                    $days = $day +1;
                    $number = Rule::select('number')->where('day',$days)->first();
                    if ($number){
                        $score = $number->number;
                    }else{
                        //不存在
                        $score = 7;
                    }
                    $status = '连续签到'.$days.'天，获得积分'.$score;
                }else if ($time >= 48*3600){
                    //表示断签 和 第一次签到是一样的
                    $days = 1;
                    $number = Rule::select('number')->where('day',$days)->first();
                    if ($number){
                        $score = $number->number;
                        //存在
                    }else{
                        //不存在
                        $score = 7;
                    }
                    $status = '断签后第一次签到，获得积分'.$score;
                }else{
                    return ['code'=>500,'msg'=>'网路错误'];
                }
            }
            //记录用户的积分明细
            Detailed::insert(['userid'=>$userId,'score'=>$score,'type'=>1,'fid'=>$signId.'订单号']);
            //求用户的积分余额
            $scores = Detailed::where('userid',$userId)->sum('score');
//            dd($days,$scores);
            //更改用户的连续签到天数 和 积分
            \App\Models\Login::where('id',$userId)->update(['days'=>$days,'scores'=>$scores]);
            //事务提交
            DB::commit();
            return ['code'=>200,'msg'=>'签到成功','data'=>
                ['score'=>$scores,'status'=>$status,'days'=>$days]];
        }catch (\Exception $e){
            //事务回滚
            DB::rollBack();
            return ['code'=>501,'msg'=>'签到失败'];
        }
    }
    /**
     * Name: 初始化
     * User: Zhao
     * Date: 2023/6/19
     * Time:10:19
     * @return array
     */
    public function signinin()
    {
        //用户ID
        $uid =1;
        $data = \App\Models\Login::where('id',$uid)->first();
        return ['code'=>200,'msg'=>'签到成功','data'=>$data];
    }

    public function sign()
    {
        $data = Rule::paginate(2);
        return $data;
    }

}
